package io.cici.cc.mybatis.lite.sql_source.scripting.tag.forEach;

import io.cici.cc.mybatis.lite.parse.TokenHandler;
import io.cici.cc.mybatis.lite.parse.TokenParser;
import io.cici.cc.mybatis.lite.session.Configuration;
import io.cici.cc.mybatis.lite.sql_source.Context;
import io.cici.cc.mybatis.lite.sql_source.scripting.tag.ForEachTag;

import java.util.Map;

public class FilteredContext extends Context {
    private final Context delegate;

    private final String itemIndex;
    private final String item;
    private final int index;

    public FilteredContext(Configuration configuration, Context delegate, String itemIndex, String item, int index) {
        super(configuration, null);
        this.delegate = delegate;
        this.itemIndex = itemIndex;
        this.item = item;
        this.index = index;
    }

    @Override
    public Map<String, Object> getBindings() {
        return delegate.getBindings();
    }

    @Override
    public void bind(String name, Object value) {
        delegate.bind(name, value);
    }

    @Override
    public String getSql() {
        return delegate.getSql();
    }

    @Override
    public void appendSql(String sql) {
        TokenParser tokenParser = new TokenParser("#{", "}", new TokenHandler() {
            @Override
            public String handle(String content) {//
                String newContent = content.replaceFirst("^\\s*" + item + "(?![^.,:\\s])", ForEachTag.itemizeItem(item, index));
                if (itemIndex != null && newContent.equals(content)) {
                    newContent = content.replaceFirst("^\\s*" + itemIndex + "(?![^.,:\\s])", ForEachTag.itemizeItem(itemIndex, index));
                }
                return "#{" + newContent + "}";
            }
        });
        delegate.appendSql(tokenParser.parse(sql));
    }

    @Override
    public int getUniqueNumber() {
        return delegate.getUniqueNumber();
    }

}
